package com.skyline.user.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.skyline.user.dao.EmailTokenDao;
import com.skyline.user.model.EmailToken;
import com.skyline.user.service.EmailTokenService;
import com.skyline.user.type.EmailTokenType;

@Service("emailService")
public class EmailTokenServiceImpl implements EmailTokenService {

	@Autowired
	private EmailTokenDao emailTokenDao;

	private EmailToken genToken(long userId, String email, EmailTokenType type) {
		EmailToken token = new EmailToken();
		Date now = new Date();
		String tokenStr = genTokenStr(userId, email, type, now);
		token.setCheckTime(now);
		token.setEmail(email);
		token.setToken(tokenStr);
		token.setType(type);
		token.setUserId(userId);
		return token;
	}

	private String genTokenStr(long userId, String email, EmailTokenType type, Date now) {
		String tokenStr = userId + "-" + email + "-" + type.toString() + "-" + now.getTime();
		tokenStr = DigestUtils.md5Hex(tokenStr);
		return tokenStr;
	}

	@Override
	public EmailToken addToken(long userId, String email, EmailTokenType type) {
		List<EmailToken> uncheckedTokens = emailTokenDao.queryTokenByEmailAndTypeAndChecked(email, type, false);
		for (EmailToken ut : uncheckedTokens) {
			emailTokenDao.updateTokenChecked(ut.getId(), true);
		}
		EmailToken token = genToken(userId, email, type);
		emailTokenDao.insertToken(token);
		return token;

	}

	@Override
	public EmailToken checkToken(String tokenStr) {
		EmailToken token = emailTokenDao.queryToken(tokenStr);
		if (token == null) {
			return null;
		}
		Date now = new Date();
		if (token.getCheckTime().getTime() - now.getTime() > (long) (24 * 3600 * 1000)) {
			return null;
		}
		if (token.isChecked()) {
			return null;
		}
		// 在这里出错了，所以我把它注释掉了
		// String generatedTokenStr=genTokenStr(token.getUserId(),
		// token.getEmail(), token.getType(), token.getCheckTime());
		// if(generatedTokenStr.equals(tokenStr)==false||tokenStr.equals(token.getToken())==false){
		// return false;
		// }
		return token;
	}

	@Override
	public void updateToken(Long id) {
		emailTokenDao.updateTokenChecked(id, true);
	}

}
